/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.transport.session;

import com.inyourcode.core.transport.session.api.Session;
import com.inyourcode.core.transport.netty.channel.NettyChannel;
import io.netty.channel.Channel;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author JackLei
 */
public class SessionService {
    private static final ConcurrentHashMap<Channel, Session> CHANNEL_SESSION_MAP = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Long, Session> ID_SESSION_MAP = new ConcurrentHashMap<>();

    public static Session create(Channel channel) {
        Session session = new BasicSession();
        session.setChannel(channel);
        CHANNEL_SESSION_MAP.put(channel, session);
        return session;
    }

    public static void create(long id, Session session) {
        ID_SESSION_MAP.put(id, session);
    }

    public static void update(Channel channel, Session session) {
        CHANNEL_SESSION_MAP.put(channel, session);
    }

    public static Session remove(Channel channel) {
        return CHANNEL_SESSION_MAP.remove(channel);
    }

    public static Session remove(Long id) {
        return ID_SESSION_MAP.remove(id);
    }

    public static Session getSessionByChannel(NettyChannel nettyChannel) {
        return CHANNEL_SESSION_MAP.get(nettyChannel.channel());
    }

    public static Session getSessionByUid(Long uid) {
        return ID_SESSION_MAP.get(uid);
    }

    public static Collection<Session> getAll() {
        return ID_SESSION_MAP.values();
    }
}
